/*
 * Copyright 2010 Clavid AG
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.clavid.example.oauth.suisseid;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Utility servlet for accessing the Clavid SuisseID OAUTH service.
 * <p>
 * @version $Id: ClavidOAuthSuisseIDServlet.java 6 2010-05-17 09:19:49Z telbie $
 */
public class ClavidOAuthSuisseIDServlet extends HttpServlet {

  private static final long serialVersionUID = 1L;

  private static final String SESSION_ATTRIBUTE_OAUTH_TOKEN_SECRET = "oauth_token_secret";
  
  private String consumerKey = null;
  private String consumerSecret = null;
  private String oauthCallback = "oob"; // out of band by default
  
  public void init() throws ServletException {
    consumerKey = getInitParameter("consumer-key");
    consumerSecret = getInitParameter("consumer-secret");
    String callback = getInitParameter("oauth-callback");
    if ((callback != null) && (callback.length() > 0)) {
      oauthCallback = callback;
    }
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    processRequest(request, response);
  }
 
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    processRequest(request, response);
  }
  
  public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.addHeader("Cache-Control", "no-cache");
    response.addHeader("Pragma", "no-cache");
    response.addDateHeader("Expires", 0);
    response.setContentType("text/html");
    try {
      HttpSession session = request.getSession();

      String pathInfo = request.getPathInfo();
      if ("/request".equals(pathInfo)) {
        
        ClavidOAuthSuisseID oauth = new ClavidOAuthSuisseID(consumerKey, consumerSecret, oauthCallback);
        
        oauth.setUserLanguage(Locale.ENGLISH);
        oauth.setRequiredAttribute(ClavidOAuthSuisseID.SUISSE_ID_NUMBER);
        oauth.setOptionalAttribute(ClavidOAuthSuisseID.SUISSE_ID_EMAIL);
        oauth.setOptionalAttribute(ClavidOAuthSuisseID.SUISSE_ID_NAME);
        
        String authorizationURL = oauth.getAuthorizationUrl();
        session.setAttribute(SESSION_ATTRIBUTE_OAUTH_TOKEN_SECRET, oauth.getTokenSecret());
        
        response.sendRedirect(authorizationURL);
        
      } else if ("/callback".equals(pathInfo)) {

        String token = request.getParameter(ClavidOAuthSuisseID.OAUTH_TOKEN);
        String tokenSecret = (String) session.getAttribute(SESSION_ATTRIBUTE_OAUTH_TOKEN_SECRET);
        session.removeAttribute(SESSION_ATTRIBUTE_OAUTH_TOKEN_SECRET);
        ClavidOAuthSuisseID oauth = new ClavidOAuthSuisseID(consumerKey, consumerSecret, token, tokenSecret);
        oauth.callAccessToken();
        
        String suisseIdNumber = oauth.getAttribute(ClavidOAuthSuisseID.SUISSE_ID_NUMBER);
        String suisseIdEmail = oauth.getAttribute(ClavidOAuthSuisseID.SUISSE_ID_EMAIL);
        String suisseIdName = oauth.getAttribute(ClavidOAuthSuisseID.SUISSE_ID_NAME);
        session.setAttribute(ClavidOAuthSuisseID.SUISSE_ID_NUMBER, (suisseIdNumber == null) ? "" : suisseIdNumber);
        session.setAttribute(ClavidOAuthSuisseID.SUISSE_ID_NAME, (suisseIdName == null) ? "" : suisseIdName);
        session.setAttribute(ClavidOAuthSuisseID.SUISSE_ID_EMAIL, (suisseIdEmail == null) ? "" : suisseIdEmail);
        response.sendRedirect(request.getContextPath() + "/index.jsp");

      } else {
        response.sendError(401, "path info must be either /request or /callback");
      }
      
    } catch (Exception e) {
      e.printStackTrace();
      response.sendError(401, "exception happened, " + e.getMessage());
    }
  }
}
